Imports Microsoft.Office.Interop
Imports Microsoft.Office.Interop.Access
Imports System.IO
Imports System.Runtime.Serialization.Formatters.Binary
Imports System.Xml
Imports System.Xml.Serialization

Public Class AccessVBARefTransformer
	Inherits BaseAccessObjectTransformer

	Private Const STR_VBA_REFS_XML_FILE As String = "vbaReferences.xml"

	Protected Overrides Sub Tranform()

		Dim writer As XmlTextWriter = Nothing
		Try
			writer = New XmlTextWriter(Me.getExportFolder & STR_VBA_REFS_XML_FILE, _
									   System.Text.Encoding.UTF8)

			writer.Formatting = Formatting.Indented
			writer.WriteStartDocument()

			writer.WriteStartElement("VbaReferences")

			For Each ref As Reference In _app.References

				If Not ref.BuiltIn Then
					writer.WriteStartElement("VbaReference")
					writer.WriteElementString("Name", ref.Name)
					writer.WriteElementString("Guid", ref.Guid)
					writer.WriteElementString("Major", CStr(ref.Major))
					writer.WriteElementString("Minor", CStr(ref.Minor))
					'writer.WriteElementString("FullPath", ref.FullPath)
                    writer.WriteEndElement()

                    Me.addObjectName(New ExportedAccessObject(ref.Name, _
                                                    SVNAccessObjectType.acVBAReference))
				End If

			Next ref
			writer.WriteEndDocument()
		Finally
			writer.Close()

		End Try


	End Sub
    Private Function hasReference(ByVal guid As String) As Boolean

        For Each ref As Reference In _app.References
            If ref.Guid = guid Then
                Return True
            End If
        Next
        Return False
    End Function

	Protected Overrides Sub LoadObjects()
		Dim myXmlDocument As XmlDocument = New XmlDocument()
		myXmlDocument.Load(Me.getExportFolder & STR_VBA_REFS_XML_FILE)
		Dim cnodes As XmlNodeList = myXmlDocument.GetElementsByTagName("VbaReference")

		For Each node As XmlNode In cnodes

			Dim guid As String = node.ChildNodes(1).InnerText
			Dim major As Integer = CInt(node.ChildNodes(2).InnerText)
			Dim minor As Integer = CInt(node.ChildNodes(3).InnerText)

			'skip DAO reference
            Try
                If (Not hasReference(guid)) Then
                    _app.References.AddFromGuid(guid, major, minor)
                End If

            Catch e As Exception
                Console.WriteLine("Error Settign VBA reference " & node.ChildNodes(0).InnerText & ": " & e.Message)
            End Try

		Next
	End Sub

	Public Overrides Function getSubfolder() As String

		Return "General"

	End Function

	Public Overrides Function getExtension() As String
		Return "xml"
	End Function

	Protected Overrides Function getAccessType() As Microsoft.Office.Interop.Access.AcObjectType

		Return Nothing

	End Function
End Class
